﻿using Colorful.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
using MongoDB.Bson;
using Colorful.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Colorful.CMS.Core;

namespace Colorful
{
    public static class CMSControllerExtensions
    {
        #region 缓存

        #region 获取Key
        public static string GetCacheKey(this Controller controller, string key)
        {
            return WebService.CacheService.GetKey(key);
        }
        #endregion

        #region 添加缓存
        public static void SetCache<T>(this Controller controller, string key, T data, TimeSpan? expiration = null)
        {
            WebService.CacheService.Set(key, data, expiration);
        }
        #endregion

        #region 获取缓存
        public static T GetCache<T>(this Controller controller, string key)
        {
            return WebService.CacheService.Get<T>(key);
        }
        /// <summary>
        /// 获取缓存，如果缓存不存在则根据回调设置缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">存储缓存的键值（如果是全局缓存前面加#）</param>
        /// <param name="updateCallback">如果缓存不存在则根据回调设置缓存</param>
        /// <param name="absoluteExpiration">过期时间</param>
        /// <param name="slidingExpiration">最后一次访问所插入对象时与该对象到期时之间的时间间隔。如果该值等效于 20 分钟，则对象在最后一次被访问 20 分钟之后将到期并被从缓存中移除。如果使用可调到期，则absoluteExpiration 参数必须为 System.Web.Caching.Cache.NoAbsoluteExpiration。</param>
        /// <param name="cacheDependency">依赖关系</param>
        /// <returns></returns>
        public static T GetCache<T>(this Controller controller, string key, Func<T> updateCallback, TimeSpan? expiration = null)
        {
            return WebService.CacheService.Get(key, updateCallback, expiration);
        }
        #endregion

        #region 移除缓存
        public static void RemoveCache(this Controller controller, string key)
        {
            WebService.CacheService.Remove(key);
        }
        #endregion

        #endregion

        #region 生成数据源
        /// <summary>
        /// 生成数据源
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="database">要访问的数据库</param>
        /// <returns></returns>
        public static void SetDataSource(this BaseController controller, List<MenuConfigField> fields)
        {
            foreach (var field in fields)
            {
                if (field.Name == "Lang")
                {
                    controller.ViewData["Lang"] = WebService.Languages;
                    continue;
                }
                if (field.DataSource == null || string.IsNullOrEmpty(field.DataSource.Data))
                    continue;
                switch (field.DataSource.DataType)
                {
                    case "Enum":
                        controller.ViewData[field.Name] = EnumHelper.ToJsonData(field.DataSource.Data).Select(a => new JsonData<string>() { id = a.id.ToString(), text = a.text }).ToList();
                        break;
                    case "Data":
                        var assembly = Assembly.GetEntryAssembly();
                        var target = (IDataSource)assembly.CreateInstance($"Colorful.Models.{field.DataSource.Data}");
                        if (target == null)
                            throw new InvalidException($"未找到数据源：{field.DataSource.Data}");
                        controller.ViewData[field.Name] = target.Datas;
                        break;
                    default:
                        controller.ViewData[field.Name] = JsonHelper.Parse<List<JsonData<int>>>(field.DataSource.Data).Select(a => new JsonData<string>() { id = a.id.ToString(), text = a.text }).ToList();
                        break;
                }
            }
        }
        #endregion

        #region 访问统计

        #endregion

        #region GetLink 生成中英文链接
        public static string GetLink(this Controller controller, string url)
        {
            return controller.HttpContext.GetLink(url);
        }
        #endregion
    }
}
